import requests
import time
# 多进程包
from multiprocessing import Process
from multiprocessing import Pool
# 多线程
from threading import Thread
import random

request_result = []


def request_baidu(index):
    global request_result
    url = "http://www.baidu.com"
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
    }
    response = requests.get(url, headers=headers)
    time.sleep(1)
    print(f"request {index}, response status: {response.status_code}")
    request_result.append(response.status_code)
    return f"{response.status_code} {index}"


# 不共享内存资源
def process_test():
    p_array = []
    for i in range(10):
        # 创建进程 target传递方法 args传递参数 元祖形式
        p = Process(target=request_baidu, args=(i,))
        # 启动进程
        p.start()
        p_array.append(p)
    # 将子进程加入到当前进程当中
    [p.join() for p in p_array]
    print("finish!")
    print(request_result)  # []


# 不共享内存资源
def process_pool_test():
    # 创建进程池  12 大小
    pool = Pool(12)
    f_array = []
    for index in range(12):
        result = pool.apply_async(request_baidu, args=(index,))
        f_array.append(result)
    # 没有这个会报错 必须要写上，不然进程池会一直运行
    pool.close()
    # 没有这个不会执行 将这个进程池加入到当前进程执行
    pool.join()
    # 获取进程返回值
    [print(f.get()) for f in f_array]
    print(request_result) # []


# 可以访问主进程的全局变量
def thread_test():
    t_array = []
    for i in range(10):
        # 创建线程
        t = Thread(target=request_baidu, args=(i,))
        # 启动线程 target方法在start后执行
        t.start()
        t_array.append(t)

    [t.join() for t in t_array]
    # t_array里面所有多线程执行完
    print("finish")
    print(request_result)


def homework(num):
    now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    time.sleep(random.randint(1, 3))
    print(f"{now_time} {num}")


if __name__ == "__main__":
    t_arr = []
    for i in range(20):
        t = Thread(target=homework, args=(i,))
        t.start()
        t_arr.append(t)
    [t.join() for t in t_arr]
    print("thread homework finish!")

    p_arr = []
    for i in range(15):
        p = Process(target=homework, args=(i,))
        p.start()
        p_arr.append(p)

    [p.join() for p in p_arr]
    print("process homework finish!")

    pool_size = 10
    p_arr = []
    pool = Pool(pool_size)
    for i in range(pool_size):
        result = pool.apply_async(homework, args=(i,))
        p_arr.append(result)
    pool.close()
    pool.join()
    [p.get() for p in p_arr]
    print("process pool homework finish")

